package com.wing.sell.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.device.model.entity.DeviceModel;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.response.ProductTypeVO;
import com.wing.product.service.DynamicService;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductTypeService;
import com.wing.sell.model.entity.*;
import com.wing.sell.model.response.OrderProVO;
import com.wing.sell.model.response.OrderVO;
import com.wing.sell.service.*;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.sell.model.request.OrderProForm;
import groovy.util.IFileNameFinder;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-销售订单产品表管理", tags = "#/sell/orderPro")
@RestController("orderProController")
@RequestMapping("sell/admin/orderPro")
@RequiredArgsConstructor
public class OrderProController {

    private final OrderProService orderProService;
    private final ProductDetailService productDetailService;
    private final OrderProReviewService orderProReviewService;
    private final OrderProEnclosureService orderProEnclosureService;

    private final ProductTypeService productTypeService;


    @ApiOperation(value = "查询所有销售订单产品表", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            , @ApiImplicitParam(name = "sort", value = "排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "order", value = "排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            , @ApiImplicitParam(name = "orderId", value = "订单ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<OrderPro> list(
            @RequestParam(defaultValue = "1") Integer page
            , @RequestParam(defaultValue = "10") Integer limit
            , @RequestParam(defaultValue = "create_time") String sort
            , @RequestParam(defaultValue = "asc") String order
            , Long orderId
    ) {

        Page<OrderPro> pg = new Page<>(page, limit);
        QueryWrapper<OrderPro> queryWrapper = new QueryWrapper<>();

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            if (StringUtils.equals("asc", order)) {
                queryWrapper.orderByAsc(StrUtil.toUnderlineCase(sort));
            } else {
                queryWrapper.orderByDesc(StrUtil.toUnderlineCase(sort));
            }
        }

        //搜索
        if (orderId != null) {
            queryWrapper.eq("order_id", orderId);
        }
        IPage<OrderPro> list = orderProService.getBaseMapper().selectPage(pg, queryWrapper);
        //包含评审环节 附件
        list.getRecords().parallelStream().forEach(k -> {
            QueryWrapper<OrderProReview> wrapper = new QueryWrapper<>();
            k.setOrderProReviewList(orderProReviewService.list(wrapper.eq("pro_id", k.getId())));
            QueryWrapper<OrderProEnclosure> query = new QueryWrapper<>();
            k.setOrderProEnclosureList(orderProEnclosureService.list(query.eq("pro_id", k.getId())));
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询销售订单的产品数据", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单ID", defaultValue = "", example = "", dataType = "Long", paramType = "query")
    })
    @GetMapping("/getOrderProVOListByOrderId")
    public JsonResult<List<OrderProVO>> getOrderProVOListByOrderId(Long orderId) {
        Map params = new HashMap();
        if (orderId != null) {
            params.put("orderId", orderId);
        }
        List<OrderProVO> list = orderProService.list4app(params);
        return JsonResult.success(list);
    }

    @ApiOperation(value = "查询客户产品详情", notes = "搜索-产品详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cusSkuId", value = "客户产品id", defaultValue = "", example = "", dataType = "Long", paramType = "query")
    })
    @GetMapping("/getOrderProId")
    public JsonResult<OrderPro> getOrderProId(@RequestParam("cusSkuId") Long cusSkuId) {
        OrderPro byId = orderProService.getById(cusSkuId);
        //1565993388131450590
        if (byId != null) {
            ProductDetail productDetailService4appById = this.productDetailService.get4appById(byId.getProductDetailId());
            byId.setProductDetail(productDetailService4appById);
        }
        ProductTypeVO productTypeVO = productTypeService.get4appById(byId.getProTypeId());
        if(productTypeVO != null){
            byId.setProTypeName(productTypeVO.getName());
        }
        return JsonResult.success(byId);
    }


    @ApiOperation(value = "查询", notes = "搜索-订单物料")
    @GetMapping("/allSkuCodeByOrderId")
    public JsonResult getSkuCodeByOrderId(@RequestParam("orderId") Long orderId){
        List<OrderPro> list = orderProService.listNotInnerInfo(orderId);
        return JsonResult.success(list);
    }


    @ApiOperation(value = "添加销售订单产品表", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(OrderProForm.Add.class) OrderProForm orderProForm) {
        if (orderProService.add(orderProForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }


    @ApiOperation(value = "修改销售订单产品表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(OrderProForm.Update.class) @RequestBody OrderProForm orderProForm) {
        OrderPro orderPro = orderProService.getById(orderProForm.getId());
        if (orderPro == null) {
            return JsonResult.fail("修改失败！");
        }
        Boolean i = orderProService.updateInfo(orderProForm);
        if (i) {
            return JsonResult.success("修改成功！");
        }else{
            return JsonResult.fail("修改失败！");
        }

    }


    @ApiOperation(value = "删除销售订单产品表", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderProId", value = "销售订单产品表id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long orderProId) {
        if (orderProService.removeById(orderProId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }


    //批量删除
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @DeleteMapping("/delBatch")
    public JsonResult delete(String ids) {
        if (StringUtils.isNotBlank(ids)) {
            List<Long> idList = new ArrayList<>();
            String[] idArray = ids.split(",");
            for (int i = 0; i < idArray.length; i++) {
                idList.add(Long.valueOf(idArray[i]));
            }
            if (orderProService.remove(new QueryWrapper<OrderPro>().in("id", idList))) {
                return JsonResult.success("删除成功");
            }
        } else {
            return JsonResult.fail("请选择数据");
        }
        return JsonResult.fail("删除失败");
    }


}
